package cn.jn.lhm.netty.part02;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/4/25 - 23:16
 **/
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                // 异步非阻塞方法 真正建立连接的是 NioEventLoop 线程
                .connect(new InetSocketAddress("localhost", 8080));

        // 1、同步阻塞当前线程直到 NIO 线程连接建立完毕
//        channelFuture.sync();
//        Channel channel = channelFuture.channel();
//        channel.writeAndFlush("hello, world");

        // 2、采取回调的方式异步处理,NIO线程处理完成后会触发监听器方法
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel1 = future.channel();
                channel1.writeAndFlush("hello, world");
                log.info("发送完成");
            }
        });
        log.info("main");
    }
}
